package com.redis.client.manage;

import com.alibaba.fastjson.JSON;
import com.redis.client.bean.Account;
import com.redis.client.bean.PersistBean;
import com.redis.client.util.JsonUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hetao
 */
public class Persistent {

    private static Persistent instance;

    private Persistent(){
        persistBean = JsonUtil.getPersistBean();
        if(persistBean == null) {
            persistBean = new PersistBean();
            persistBean.setList(new ArrayList<>(4));
        }
    }

    public static Persistent getInstance() {
        if (instance == null) {
            instance = new Persistent();
        }
        return instance;
    }

    PersistBean persistBean;

    public Map<String, Account> getMap() {
        List<Account> accountList = persistBean.getList();
        Map<String, Account> map = new HashMap<>(4);
        for (Account account : accountList) {
            map.put(account.getName(), account);
        }
        return map;
    }

    public boolean existName(String name) {
        Map<String, Account> map = getMap();
        return map.containsKey(name);
    }

    public boolean addAccount(Account account) {
        if(existName(account.getName())) {
            return false;
        }
        persistBean.getList().add(account);
        JsonUtil.setPersistBean(persistBean);
        return true;
    }

    public List<Account> getAccounts() {
        return  persistBean.getList();
    }
}
